// 引入数据模型
const { Comment, User } = require("../model/index")

/**
 * 获取指定商品的评论
 * @param { Object } itemId->商品id ，pageNum->页码，pageSize->页容量
 * @returns 
 */
exports.getItemAllComments = async function ({ itemId, pageNum = 1, pageSize = 5 }) {
  if (!itemId) {
    return
  }
  const result = await Comment.findAndCountAll({
    where: {
      itemId
    },
    limit: pageSize,
    offset: (pageNum - 1) * pageSize,
    include: {
      model: User,
      // attributes: []
    }
  })

  const { count } = result
  const comments = result.rows.map(com => {
    com.user = com.User
    return com
  })
  return {
    count, // 总条数
    comments, // 评论
    pageNum, // 页码
    pageSize // 页容量
  }
}

/**
 * 添加评论
 * @returns -> Object
 */
exports.addComment = async function ({ itemId, userId, content }) {
  const result = await Comment.create({
    itemId,
    userId,
    content
  })
  return result
}
